
import { IncomingMessage, ServerResponse } from "http";
import fs from 'fs';
import path from 'path';

export const templateList = async (req: IncomingMessage, res: ServerResponse) => {
    const list = getDirectories(path.join(__dirname, '../../module.template'));

    // 获取json文件
    const jsonList = list.map(e => {
        const id = path.basename(e);
        const filePath = path.join(e, 'index.json');
        const json = fs.readFileSync(filePath, 'utf-8');
        return { ...JSON.parse(json), id, file: undefined };
    });

    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(jsonList));
}

function getDirectories(source: string): string[] {
    return fs.readdirSync(source, { withFileTypes: true })
        .filter(dirent => dirent.isDirectory())
        .map(dirent => path.join(source, dirent.name));
}